//The MIT License
//
//Copyright (c) 2009 nodchip
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
package tv.dyndns.kishibe.client.creation;

import java.util.Set;

import tv.dyndns.kishibe.client.Service;

import com.google.gwt.user.client.rpc.AsyncCallback;

public class CheckerTegaki extends Checker {
	private static Set<String> availableCharacters = null;

	private static final AsyncCallback<Set<String>> callbackGetAvailableChalacters = new AsyncCallback<Set<String>>() {
		public void onSuccess(Set<String> result) {
			availableCharacters = result;
		}

		public void onFailure(Throwable caught) {
		}
	};

	public CheckerTegaki(PanelProblemCreation panelProblemCreation) {
		super(panelProblemCreation);

		if (availableCharacters == null) {
			Service.Util.getInstance().getAvailableChalactersForHandwriting(callbackGetAvailableChalacters);
		}
	}

	protected boolean check(WidgetProblemForm form) {
		boolean result = super.check(form);

		if (availableCharacters == null) {
			result = false;
			warn("使用可能な文字リストが取得されていません。しばらくお待ちください。");
		}

		final int numberOfAnswers = form.getNumberOfAnswers();
		if (numberOfAnswers == 0) {
			warn("解答を入力してください");
			result = false;
		}

		for (int answerIndex = 0; answerIndex < numberOfAnswers; ++answerIndex) {
			final String answer = form.getTextBoxAnswer(answerIndex);
			for (int characterIndex = 0; characterIndex < answer.length(); ++characterIndex) {
				final String s = answer.substring(characterIndex, characterIndex + 1);

				if (!availableCharacters.contains(s)) {
					warn((answerIndex + 1) + "番目の解答" + (characterIndex + 1) + "文字目「" + s + "」は使用できません。");
					result = false;
				}
			}
		}

		return result;
	}
}
